Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

289
Visualizações
Firefox and Google Chrome differences creating or sorting an array using .sort(() => Math.random() - 0.5);

I'm trying to make a minesweeper, and something weird has happened, in Chrome or Chromium-based navigators everything seems and works just fine, but in firefox, all of the bombs generated clumped together at the end, or the start of the array, is there any difference in how sort() works with parameters?

I'll leave the piece of the code that generates the board.

  

    function createBoard() {
        //create an array with shuffled bombs
        const bombsArray = Array(bombAmount).fill("bomb");
        const emptyArray = Array(width * width - bombAmount).fill("valid");
        const gameArray = emptyArray.concat(bombsArray);
        const shuffledArray = gameArray.sort(() => Math.random() - 0.5);
        for (let i = 0; i < width * width; i++) {
          const square = document.createElement("div");
          square.setAttribute("id", i);
          square.classList.add(shuffledArray[i])
          grid.appendChild(square);
          squares.push(square);

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

From the documentation:

Note: compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments.

In your case, you don't do this, which gives undefined behaviour, most likely dependent on the sorting algorithm that is used by the browser's Array.sort implementation.

You can ensure that the random value for a particular array item remains stable by mapping to a new array with a random order property, sorting, then mapping back again:

const shuffledArray = gameArray
  .map((value) => ({ value, order: Math.random() }))
  .sort((a, b) => a.order - b.order)
  .map(({ value }) => value)

This probably isn't the most efficient way of shuffling an array, but a minesweeper board is so small that it won't matter.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda